package com.adam.example.aggregation.bucket;

import com.adam.example.TransportClientHolder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.range.date.DateRangeAggregationBuilder;

import java.net.UnknownHostException;

public class DateRangeAggregationExample {

    public static void main(String[] args) throws UnknownHostException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();

        DateRangeAggregationBuilder dateRangeAggregationBuilder = AggregationBuilders.dateRange("agg")
                .field("publish_time").format("yyyy-MM-dd").addUnboundedTo("now-24M/M").addUnboundedFrom("now+24M/M");
        SearchResponse searchResponse = transportClient.prepareSearch("test_books")
                        .setSize(0).addAggregation(dateRangeAggregationBuilder).get();
        Range range = searchResponse.getAggregations().get("agg");
        for(Range.Bucket bucket: range.getBuckets()) {
            System.out.println(bucket.getKey() + "(" + bucket.getFrom() + "-" + bucket.getTo() + "):" + bucket.getDocCount());
            //getFrom/getTo返回的是org.joda.time.DateTime类型，unBounded对应null
        }

        transportClient.close();
    }

}
